// components/performance/index.js
import recipeApi from '../../api/recipe';
import {
  useToast
} from '../../miniprogram_npm/miniprogram-vc-components/toast/useToast';
import {
  LOCALSTORAGE_KEY_PERFORMANCE
} from '../../dataSource';
import moment from 'moment'
import {
  list,
  add,
  remove,
  removeById

} from '../../api/performce'

let toast, t;
const form = {
  siliconAluminiumRatio: {
    type: '硅铝比',
    value: '',
    rep: '硅铝比 = 硅/铝'
  },
  qualityCoefficientOfExpansion: {
    type: '质量分数膨胀系数',
    value: '',
    rep: '质量分数膨胀系数(所有质量分数膨胀系数之和)'
  },
  mooreCoefficientOfExpansion: {
    type: '摩尔成分膨胀系数',
    value: '',
    rep: '摩尔成分膨胀系数(所有摩尔成分膨胀系数之和)'
  },

  initTemperature: {
    type: '始融温度',
    value: '',
    rep: '始融温度 = ( ( 10* m +n )/2 -x )*y +z'
  },
  firingTemperature: {
    type: '烧成温度',
    value: '',
    rep: '烧成温度 = 熔融温度 + 修正量'
  },
  highTemperatureViscosity: {
    type: '高温黏度',
    value: '',
    rep: '高温黏度 = Log(920/(kz-0.32),10)'
  },
  surfaceTension: {
    type: '表面张力',
    value: '',
    rep: '表面张力 = \n sum(Y900)-0.04(Tg(配方的烧成温度)-900) \n 高温粘度为0时，该值无意义'
  }
  // kz: {
  //   type: '粘度系数',
  //   value: '',
  //   rep: '粘度系数Kz = \n(100/(氧化硅质量分数+氧化质铝氧化铝量分数))-1'
  // },
  // meltingTemperature: {
  //   type: '熔融温度',
  //   value: '',
  //   rep: '熔融温度 = (m-0.35)*125 + (n-3)*12.5 +1250'
  // }
};

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    candidate: {
      type: Boolean,
      value: false
    },
    dataSource: {
      type: Array,
      value: [],
      observer(data) {
        if (data && data.length > 0) {
          this.getSelectList(data);
        }
      }
    },
    disabled: {
      type: Boolean,
      value: false
    },
    computedOnly: {
      type: Boolean,
      value: false
    },
    data: {
      type: Object,
      value: {},
      observer(data) {
        const {
          tRongCorrectionValue,
          x,
          y,
          z,
          performanceData
        } = data;
        const f = this.data.form;
        if (performanceData) {
          for (let x in f) {
            f[x]['value'] = this.format(performanceData[x]);
          }
        }
        this.setData({
          tRongCorrectionValue,
          x,
          y,
          z,
          computedProps: performanceData,
          form: f
        })
      }
    },
    ingredientsList: {
      type: Array,
      value: []
    },
    showList: {
      type: Boolean,
      value: true
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    tRongCorrectionValue: '',
    x: '',
    y: '',
    z: '',
    activeName: '',
    fields: Object.keys(form),
    form,
    showMore: false,
    computedProps: {},
    loading: false,
    dataSourceCheck: {},
    performanceCheckShow: false,
    expand: false,
    selectList: []
  },

  /**
   * 组件的方法列表
   */
  methods: {
    toggle() {
      this.setData({
        expand: !this.data.expand
      })
    },
    computedData(event) {
      let data = event.detail.value,
        saved = event.detail.target.dataset.save;
      for (let x in data) {
        if (data[x]?.length < 1) {
          data[x] = null;
        }
      }
      if (this.properties.dataSource?.length < 1) {
        toast.init({
          value: "请先添加原料及填写份额",
          position: 'center'
        }).open();
        return
      }
      const recipeCombination = this.properties.dataSource.map(it => {
        return {
          ingredients: {
            id: it.value
          },
          number: it.number
        }
      })
      const params = {
        ...data,
        recipeCombination
      }
      recipeApi.getPerformance(params, res => {
        let f3 = this.data.form;
        for (let it of this.data.fields) {
          f3[it].value = this.format(res['performanceData'][it])
        }

        const _data = {
          ... this.properties.data,
          id: this.properties.data['recipeId'] || this.properties.data['id'],
          computedProps: res['performanceData'],
          
          form: f3,
          x: res['x'],
          y: res['y'],
          z: res['z'],
          tRongCorrectionValue: res['tRongCorrectionValue']
        };
        this.setData(_data);

        saved && this.saveData(_data);
      })
    },
    switchItem(event) {
      this.setData({
        activeName: event.detail,
      });
    },
    showMoreHandle() {
      this.setData({
        showMore: !this.data.showMore
      })
    },
    /**处理小数点 */
    format(data) {
      if (data) {
        return parseFloat(data).toFixed(2);
      }
      return 0
    },
    getSelectList(data) {
      if (this.properties.ingredientsList.length < 1) {
        clearTimeout(t);
        t = setTimeout(() => {
          this.getSelectList(data)
        }, 500)
        return
      }
      const list = this.properties.ingredientsList.filter(it => {
        return data.map(k => k.value).includes(it.id)
      });
      this.setData({
        selectList: list.map(it => {
          return {
            number: this.properties.dataSource.find(k => {
              return k.value === it.id
            })?.number,
            ingredients: it
          }
        })
      })

    },
    onInput(event) {
      const value = event.detail,
        name = event.currentTarget.dataset.name;
      this.triggerEvent('input', {
        name,
        value
      });
    },
    saveData(data) {
      let date = moment().format("YYYY-MM-DD HH:mm:ss");
      wx.showModal({
        showCancel: false,
        editable: true,
        placeholderText: date,
        title: '输入一个名称，或者缺省使用系统当前日期和时间命名',
        success: res => {

          if (res.confirm) {
            this.setData({
              loading: true
            })
            // const newData = JSON.parse(JSON.stringify(this.properties.data));
            const {
              x,
              y,
              z,
              tRongCorrectionValue
            } = data;

            const nd = {
              ...data,
              x,
              y,
              z,
              tRongCorrectionValue,
              name: res.content || date,
              performanceData: data.computedProps,
              recipeCombination: this.data.selectList,
              copy: true
            }
            add(nd, () => {

              this.fetchList();
            })
          }
        }
      })
    },
    onFocus() {
      this.triggerEvent('focus');
    },
    onBlur() {
      this.triggerEvent('blur');
    },
    onDelect() {
      wx.showModal({
        title: '提示',
        content: '确定要删除除候选外的其它所有数据吗？',
        success: (res) => {
          if (res.confirm) {
            this.properties.showList ? remove({
              recipeId: this.properties.data.recipeId || this.properties.data.id
            }, () => {
              this.triggerEvent('delete', 'all')
            }) : removeById(this.properties.data, () => {
              this.triggerEvent('delete', this.properties.data.id)
            })
          }
        }
      })
    },
    getLocalData() {
      return wx.getStorageSync(LOCALSTORAGE_KEY_PERFORMANCE) || [];
    },
    fetchList() {
      list({
        recipeId: this.properties.data.recipeId || this.properties.data.id
      }, (res = []) => {
        this.setData({
          loading: false
        })
        wx.showToast({
          title: '已保存',
          icon: 'none'
        })
        this.triggerEvent('create-data', res);
      })
    },
    onConfirm(event) {
      const {
        value
      } = event.detail;

      this.hidePicker();

      this.setData({
        dataSourceCheck: {
          ...value.data,
          text: value.text
        }
      })
      this.showPerformanceCheck();
    },
    showPerformanceCheck() {
      this.triggerEvent('change', this.data.dataSourceCheck);
    },
    hidePerformanceCheck() {
      this.setData({
        performanceCheckShow: false
      })
    }
  },
  lifetimes: {
    attached() {
      toast = useToast('#toast', this);
    }
  }
})